package tools.mysql;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.zhixiang.core.util.FileUtils;


public class DBUtils
{
    /**
     * 获得mysql的安装根目录
     * @return
     */
    public static String getMysqlHome(SessionFactory sessionFactory)
    {
        Session session = sessionFactory.openSession();
        SQLQuery sqlQuery = session.createSQLQuery("select @@basedir as basePath from dual");
        List list = sqlQuery.list();
        Object obj = list.get(0);
        String mysqlHome = String.valueOf(obj);
        session.close();
        return mysqlHome;
    }
    

    /**
     * 获得mysql的安装根目录
     * @return
     */
    public static String getDBName(SessionFactory sessionFactory)
    {
        Session session = sessionFactory.openSession();
        SQLQuery sqlQuery = session.createSQLQuery("select database()");
        List list = sqlQuery.list();
        Object obj = list.get(0);
        String dbName = String.valueOf(obj);
        session.close();
        return dbName;
    }

    public static Properties getProperties()
    {
        try {
            Properties properties = new Properties();
            String classPath = DBUtils.class.getResource("/").getPath().substring(1);
            classPath = classPath.replace("test-classes","classes");
            properties.load(new FileInputStream(classPath + "/conf/jdbc.properties"));
            return properties;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getUserName(Properties properties)
    {
        if(properties != null) {
            return properties.getProperty("jdbc.username");
        }else{
            return null;
        }
    }

    public static String getPassword(Properties properties)
    {
        if(properties != null) {
            return properties.getProperty("jdbc.password");
        }else{
            return null;
        }
    }


    /**
     * 用source命令导入存储过程
     * @param mysqlHome
     * @param absolutePath
     */
    public static void mysqlimport(String mysqlHome, String dbName, String absolutePath)
    {
        BufferedInputStream in = null;
        BufferedReader inBr = null;
        try
        {
            mysqlHome = mysqlHome.replace("\\", "/");
            Properties properties = getProperties();
            String userName = getUserName(properties);
            String passord = getPassword(properties);
            //            String cmd = "cmd /c " + mysqlHome + "/bin/mysql -uroot -proot bjjk < " + fileFullName;// pass
            //            String cmd = mysqlHome + "bin/mysql -uroot -proot --default-character-set=utf8 --database=bjjk --delimiter=$$ -e\"source " + absolutePath + "\"";
            //兼容mysql路径中含有空格的情况
            String cmd = "\"" + mysqlHome + "bin/mysql\" -u"+userName+" -p"+passord+" --default-character-set=utf8 --database=" + dbName + " --delimiter=$$ -e\"\\. " + absolutePath + "\"";
            System.out.println(cmd);
            Process ps = Runtime.getRuntime().exec(cmd);

            in = new BufferedInputStream(ps.getErrorStream());
            inBr = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String lineStr;
            while ((lineStr = inBr.readLine()) != null)
                // 获得命令执行后在控制台的输出信息
                System.out.println(lineStr);// 打印输出信息
            // 检查命令是否执行失败。
            if (ps.waitFor() != 0)
            {
                if (ps.exitValue() == 1) // p.exitValue()==0表示正常结束，1：非正常结束
                    System.err.println("命令执行失败!");
            }

        }
        catch (InterruptedException | IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (in != null)
            {
                try
                {
                    in.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            if (in != null)
            {
                try
                {
                    inBr.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 递归查找baseDir下所有目录中的sql文件
     */
    public static List<File> getFiles(File basefile)
    {
        List<File> fileList = new ArrayList<File>();
        File[] files = basefile.listFiles();
        for (File file : files)
        {
            if (file.isDirectory())
            {
                fileList.addAll(getFiles(file));
            }
            else if (file.isFile())
            {
                String extensionName = FileUtils.getExtensionName(file.getName());
                if ("sql".equalsIgnoreCase(extensionName))
                {
                    fileList.add(file);
                }
            }
        }
        return fileList;
    }
    
    /**
     * 递归查找baseDir下所有目录中的sql文件
     */
    public static List<File> getFiles(File basefile,String[] excludeFolder)
    {
        List<File> fileList = new ArrayList<File>();
        File[] files = basefile.listFiles();
        for (File file : files)
        {
            String fileName = file.getName();
            if (file.isDirectory())
            {
                if(!Arrays.asList(excludeFolder).contains(fileName)){
                    fileList.addAll(getFiles(file));
                }
            }
            else if (file.isFile())
            {
                String extensionName = FileUtils.getExtensionName(fileName);
                if ("sql".equalsIgnoreCase(extensionName))
                {
                    fileList.add(file);
                }
            }
        }
        return fileList;
    }
}
